package com.ccb.sc.common.modules.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
//psl import com.ccb.sc.common.bind.exception.BizException;
import com.ccb.sc.common.code.BizCodeFace;
import com.ccb.sc.common.code.ErrorCode;
import com.ccb.sc.common.constant.CommonConstant;
import com.ccb.sc.common.modules.common.entity.LogisticsCompany;
import com.ccb.sc.common.modules.common.service.IDeliveryService;
import com.ccb.sc.common.modules.common.service.ILogisticsCompanyService;
import com.ccb.sc.common.modules.common.service.IRedisService;
import com.ccb.sc.common.modules.common.vo.QueryTrackResp;
import com.ccb.sc.common.modules.goods.entity.Goods;
import com.ccb.sc.common.modules.goods.entity.GoodsComment;
import com.ccb.sc.common.modules.goods.entity.GoodsSpecs;
import com.ccb.sc.common.modules.goods.enums.GoodsType;
import com.ccb.sc.common.modules.goods.mapper.GoodsCommentMapper;
import com.ccb.sc.common.modules.goods.mapper.GoodsMapper;
import com.ccb.sc.common.modules.goods.mapper.GoodsSpecsMapper;
import com.ccb.sc.common.modules.groupon.entity.GrouponLog;
import com.ccb.sc.common.modules.groupon.enums.GrouponStatus;
import com.ccb.sc.common.modules.groupon.service.GrouponLogService;
import com.ccb.sc.common.modules.groupon.service.GrouponService;
import com.ccb.sc.common.modules.member.entity.Member;
import com.ccb.sc.common.modules.member.enums.MemberPointsLogType;
import com.ccb.sc.common.modules.member.mapper.MemberMapper;
import com.ccb.sc.common.modules.member.service.MemberPointsService;
import com.ccb.sc.common.modules.order.entity.Order;
import com.ccb.sc.common.modules.order.entity.OrderComment;
import com.ccb.sc.common.modules.order.entity.OrderItem;
import com.ccb.sc.common.modules.order.entity.OrderLog;
import com.ccb.sc.common.modules.order.enums.CommentStatus;
import com.ccb.sc.common.modules.order.enums.DeliverStatus;
import com.ccb.sc.common.modules.order.enums.OrderLogType;
import com.ccb.sc.common.modules.order.enums.OrderStatus;
import com.ccb.sc.common.modules.order.mapper.OrderLogMapper;
import com.ccb.sc.common.modules.order.mapper.OrderMapper;
import com.ccb.sc.common.modules.order.service.IOrderCommentService;
import com.ccb.sc.common.modules.order.service.IOrderItemService;
import com.ccb.sc.common.modules.order.service.IOrderService;
import com.ccb.sc.common.modules.payment.entity.Payment;
import com.ccb.sc.common.modules.payment.enums.OrderType;
import com.ccb.sc.common.modules.payment.enums.PaymentMethod;
import com.ccb.sc.common.modules.payment.enums.PaymentStatus;
import com.ccb.sc.common.modules.payment.service.PaymentService;
import com.ccb.sc.common.modules.setting.service.ISettingsService;
import com.ccb.sc.common.modules.setting.vo.OrderSettingsVo;
import com.ccb.sc.common.modules.shopkeeper.entity.Shopkeeper;
import com.ccb.sc.common.modules.shopkeeper.entity.ShopkeeperGoods;
import com.ccb.sc.common.modules.shopkeeper.entity.ShopkeeperGoodsSpecs;
import com.ccb.sc.common.modules.shopkeeper.enums.ShopkeeperPointsLogType;
import com.ccb.sc.common.modules.shopkeeper.mapper.ShopkeeperGoodsMapper;
import com.ccb.sc.common.modules.shopkeeper.mapper.ShopkeeperGoodsSpecsMapper;
import com.ccb.sc.common.modules.shopkeeper.service.ShopkeeperPointsLogService;
import com.ccb.sc.common.modules.shopkeeper.service.ShopkeeperService;
import com.ccb.sc.common.util.MoneyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ken
 * @since 2020-09-25
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private IOrderItemService orderItemService;
    private OrderLogMapper orderLogMapper;
    private ShopkeeperGoodsMapper shopkeeperGoodsMapper;
    private ShopkeeperGoodsSpecsMapper shopkeeperGoodsSpecsMapper;
    private GoodsMapper goodsMapper;
    private GoodsSpecsMapper goodsSpecsMapper;
    private GoodsCommentMapper goodsCommentMapper;
    private ILogisticsCompanyService logisticsCompanyService;
    private IDeliveryService deliveryService;
    private IOrderCommentService orderCommentService;
    private MemberMapper memberMapper;
    private ISettingsService settingsService;
    private ShopkeeperPointsLogService shopkeeperPointsLogService;
    private ShopkeeperService shopkeeperService;
    private MemberPointsService memberPointsService;
    private GrouponService grouponService;
    private PaymentService paymentService;
    private IRedisService redisService;
    private GrouponLogService grouponLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(String orderId) {
        Order order = this.getById(orderId);
        if (order == null || !order.getStatus().equals(OrderStatus.WAIT_PAY)) {
            return;
        }
        returnBalanceAndStock(order);
    }

    private void returnBalanceAndStock(Order order) {
        // 取消锁定余额
        if (Objects.equals(order.getOrderType(), OrderType.MALL)) {
            // todo 修改店主端积分抵扣字段
            if (order.getPointsDeductAmount().compareTo(BigDecimal.ZERO) > 0) {
                Shopkeeper shopkeeper = this.shopkeeperService.findByMemberId(order.getMemberId());
                this.shopkeeperPointsLogService.award(shopkeeper.getId(), order.getPointsDeductAmount(),
                        ShopkeeperPointsLogType.MALL_BACK, order.getId(), order.getMemberId());
            }
        }else if (Objects.equals(order.getOrderType(), OrderType.GROUPON)) {
            if (order.getWalletDeductAmount().compareTo(BigDecimal.ZERO) > 0) {
                Shopkeeper shopkeeper = this.shopkeeperService.findByMemberId(order.getMemberId());
                this.shopkeeperPointsLogService.award(shopkeeper.getId(), order.getWalletDeductAmount(),
                        ShopkeeperPointsLogType.GROUPON_BACK, order.getId(), order.getMemberId());
            }

            // 取消积分余额
            if (order.getPointsDeductAmount().compareTo(BigDecimal.ZERO) > 0) {
                this.memberPointsService.award(order.getMemberId(), order.getUsePoints().intValue(), MemberPointsLogType.GROUPON_RETURN, order.getId());
            }
        }else {
            if (order.getWalletDeductAmount().compareTo(BigDecimal.ZERO) > 0) {
                Shopkeeper shopkeeper = this.shopkeeperService.findByMemberId(order.getMemberId());
                this.shopkeeperPointsLogService.award(shopkeeper.getId(), order.getWalletDeductAmount(),
                        ShopkeeperPointsLogType.MALL_BACK, order.getId(), order.getMemberId());
            }

            // 取消积分余额
            if (order.getPointsDeductAmount().compareTo(BigDecimal.ZERO) > 0) {
                this.memberPointsService.award(order.getMemberId(), order.getUsePoints().intValue(), MemberPointsLogType.MALL_RETURN, order.getId());
            }
        }

        // 返还库存
        List<OrderItem> orderItems = this.orderItemService.findByOrderId(order.getId());
        for (OrderItem orderItem : orderItems) {
            if (Objects.equals(order.getOrderType(), OrderType.MALL)) {
                ShopkeeperGoodsSpecs goodsSpecs = this.shopkeeperGoodsSpecsMapper.selectById(orderItem.getGoodsSpecId());
                if (goodsSpecs == null) {
                    continue;
                }
                goodsSpecs.setStock(goodsSpecs.getStock() + orderItem.getQuantity());
                goodsSpecs.setSales(goodsSpecs.getSales() - orderItem.getQuantity());
                goodsSpecs.setVersion(goodsSpecs.getVersion());
                int updateGoods = this.shopkeeperGoodsSpecsMapper.updateById(goodsSpecs);
                if (updateGoods < 1) {
                    //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
                }
                // 减少销量
                ShopkeeperGoods goods = this.shopkeeperGoodsMapper.selectById(goodsSpecs.getGoodsId());
                if (goods != null) {
                    int sales = Optional.ofNullable(goods.getSales()).orElse(0) - orderItem.getQuantity();
                    sales = Math.max(sales, 0);
                    goods.setSales(sales);
                    this.shopkeeperGoodsMapper.updateById(goods);
                }
            }else {
               GoodsSpecs goodsSpecs = this.goodsSpecsMapper.selectById(orderItem.getGoodsSpecId());
                if (goodsSpecs == null) {
                    continue;
                }
                goodsSpecs.setStock(goodsSpecs.getStock() + orderItem.getQuantity());
                goodsSpecs.setSales(goodsSpecs.getSales() - orderItem.getQuantity());
                goodsSpecs.setVersion(goodsSpecs.getVersion());
                int updateGoods = this.goodsSpecsMapper.updateById(goodsSpecs);
                if (updateGoods < 1) {
                    //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
                }
                // 减少销量
                Goods goods = this.goodsMapper.selectById(goodsSpecs.getGoodsId());
                if (goods != null) {
                    int sales = Optional.ofNullable(goods.getSales()).orElse(0) - orderItem.getQuantity();
                    sales = Math.max(sales, 0);
                    goods.setSales(sales);
                    this.goodsMapper.updateById(goods);
                }
            }
        }

        // 更新订单记录
        order.setStatus(OrderStatus.CANCELED);
        order.setExpiryTime(null);
        boolean updateOrder = this.updateById(order);
        if (!updateOrder) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 记录日志
        OrderLog log = new OrderLog();
        log.setOrderId(order.getId());
        log.setOrderType(order.getOrderType());
        log.setType(OrderLogType.CANCEL);
        log.setMemo("订单取消");
        int insert = this.orderLogMapper.insert(log);
        if (insert < 1) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceive(String orderId) {
        Order order = this.getById(orderId);
        Assert.isTrue(DeliverStatus.SHIPPED.equals(order.getDeliverStatus()), "订单状态异常");
        LocalDateTime now = LocalDateTime.now();
        order.setStatus(OrderStatus.RECEIVED);
        /*if (OrderType.MALL.equals(order.getOrderType())) {
            order.setStatus(OrderStatus.RECEIVED);
        }else if (OrderType.POINTS.equals(order.getOrderType())) {
            order.setFinishTime(now);
            order.setStatus(OrderStatus.FINISHED);
        }*/

        order.setReceiverTime(now);
        order.setDeliverStatus(DeliverStatus.RECEIVED);
        boolean result = this.updateById(order);
        if (!result) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOrderType(order.getOrderType());
        orderLog.setType(OrderLogType.RECEIVED);
        orderLog.setMemo("订单确认收货");
        int insert = this.orderLogMapper.insert(orderLog);
        if (insert < 1) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void comment(String orderId) {
        Order order = this.getById(orderId);
        Assert.isTrue(DeliverStatus.RECEIVED.equals(order.getDeliverStatus()) && CommentStatus.WAIT_COMMENT.equals(order.getCommentStatus()), "订单状态异常");
        /*if (OrderType.MALL.equals(order.getOrderType())) {
            order.setStatus(OrderStatus.COMMENT);
        }*/
        order.setStatus(OrderStatus.COMMENT);
        order.setCommentTime(LocalDateTime.now());
        order.setCommentStatus(CommentStatus.COMMENT);
        boolean updateOrder = this.updateById(order);
        if (!updateOrder) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 判断订单是否已评价
        OrderComment existOrderComment = this.orderCommentService.findByOrderId(orderId);
        if (existOrderComment != null) {
            return;
        }

        OrderComment orderComment = new OrderComment();
        orderComment.setOrderId(orderId);
        orderComment.setPackageScore(5);
        orderComment.setServiceScore(5);
        orderComment.setShippingScore(5);
        boolean result = this.orderCommentService.save(orderComment);
        if (!result) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        Member member = this.memberMapper.selectById(order.getMemberId());
        List<OrderItem> orderItems = this.orderItemService.findByOrderId(orderId);

        GoodsType goodsType = null;
        if (OrderType.MALL.equals(order.getOrderType())) {
            goodsType = GoodsType.SHOPKEEPER_GOODS;
        }else if (OrderType.POINTS.equals(order.getOrderType())) {
            goodsType = GoodsType.POINTS_GOODS;
        }

        for (OrderItem orderItem : orderItems) {
            GoodsComment goodsComment = new GoodsComment();
            goodsComment.setContent("默认好评");
            goodsComment.setScore(5);
            goodsComment.setGoodsId(orderItem.getGoodsId());
            goodsComment.setGoodsName(orderItem.getGoodsName());
            goodsComment.setGoodsSpecsName(orderItem.getGoodsSpec());
            goodsComment.setGoodsSpecsId(orderItem.getGoodsSpecId());
            goodsComment.setCommentId(orderComment.getId());
            goodsComment.setMemberId(member.getId());
            goodsComment.setNickname(member.getNickname());
            goodsComment.setAvatar(member.getAvatar());
            goodsComment.setIsShow(true);

            goodsComment.setGoodsType(goodsType);
            int goodsCommentResult = this.goodsCommentMapper.insert(goodsComment);
            if (goodsCommentResult < 1) {
                //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
            }
        }

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOrderType(order.getOrderType());
        orderLog.setType(OrderLogType.COMMENT);
        orderLog.setMemo("订单评价");
        int insert = this.orderLogMapper.insert(orderLog);
        if (insert < 1) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(String orderId) {
        Order order = this.getById(orderId);
        //Assert.isTrue(OrderStatus.WAIT_RECEIVED.equals(order.getStatus()) && DeliverStatus.SHIPPED.equals(order.getDeliverStatus()), "订单状态异常");
        order.setFinishTime(LocalDateTime.now());
        order.setStatus(OrderStatus.FINISHED);
        boolean result = this.updateById(order);
        if (!result) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOrderType(order.getOrderType());
        orderLog.setType(OrderLogType.FINISH);
        orderLog.setMemo("订单完成");
        int insert = this.orderLogMapper.insert(orderLog);
        if (insert < 1) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        if (Objects.equals(order.getOrderType(), OrderType.MALL)) {
            // 奖励阳光值
            Shopkeeper shopkeeper = this.shopkeeperService.findByMemberId(order.getMemberId());
            this.shopkeeperPointsLogService.award(shopkeeper.getId(), order.getRewardPoints(), ShopkeeperPointsLogType.MALL_REWARD, orderId, order.getMemberId());
        }else if (Objects.equals(order.getOrderType(), OrderType.POINTS)) {
            // 计算奖励积分
            BigDecimal realAmount = order.getRealAmount();
            OrderSettingsVo orderSettingsVo = this.settingsService.getSettings(OrderSettingsVo.class);
            BigDecimal amountExchangePoints = Optional.ofNullable(orderSettingsVo.getAmountExchangePoints()).orElse(BigDecimal.TEN);
            BigDecimal divide = order.getRealAmount().divide(amountExchangePoints, 0, RoundingMode.FLOOR);
            this.memberPointsService.award(order.getMemberId(), divide.intValue(), MemberPointsLogType.ORDER_RETURN_POINTS, orderId);
        }else if (Objects.equals(order.getOrderType(), OrderType.GROUPON)) {
            // 计算团长奖励积分
            Long inviteId = order.getInviteId();
            if (inviteId == null || inviteId == 0L) {
                return;
            }
            Member member = this.memberMapper.selectById(inviteId);
            if (!member.getIsHeads()) {
                log.warn("订单[{}]完成,但邀请人[{}]不是团长", orderId, inviteId);
                return;
            }
            Shopkeeper shopkeeper = this.shopkeeperService.findByMemberId(inviteId);
            if (shopkeeper == null) {
                log.error("数据异常，用户[{}]是团长,但店主表无数据，需补偿数据", order.getMemberId());
                return;
            }
            BigDecimal amount = order.getAmount();
            OrderSettingsVo orderSettingsVo = this.settingsService.getSettings(OrderSettingsVo.class);
            BigDecimal headsRatio = Optional.ofNullable(orderSettingsVo.getHeadsRatio()).orElse(new BigDecimal("5"));
            BigDecimal headsAward = amount.multiply(headsRatio).divide(CommonConstant.HUNDRED, 2, RoundingMode.HALF_UP);
            this.shopkeeperPointsLogService.award(shopkeeper.getId(), headsAward, ShopkeeperPointsLogType.INVITE_GROUPON, orderId, order.getMemberId());
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliver(String orderId, String logisticsCompany, String logisticsNo) {
        Order order = this.getById(orderId);
        Assert.isTrue(order != null && DeliverStatus.WAIT_DELIVER.equals(order.getDeliverStatus()), "订单状态异常");
        // 判断团购订单是否已成团
        if (Objects.equals(order.getOrderType(), OrderType.GROUPON)) {
            GrouponLog grouponLog = this.grouponService.findByOrderId(orderId);
            if (grouponLog != null && !Objects.equals(grouponLog.getStatus(), GrouponStatus.FINISHED)) {
                //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.DATE_NULL).message("团购订单暂未成团!"));
            }
        }

        if (!"-1".equals(logisticsCompany)) {
            Assert.isTrue(StringUtils.hasText(logisticsNo), "物流单号不能为空");
            LogisticsCompany company = this.logisticsCompanyService.findByCode(logisticsCompany);
            Assert.notNull(company, "物流公司不存在");
            logisticsCompany = company.getName();
        }

        order.setDeliverTime(LocalDateTime.now());
        order.setStatus(OrderStatus.SHIPPED);
        order.setDeliverStatus(DeliverStatus.SHIPPED);
        order.setLogisticsCompany(logisticsCompany);
        order.setLogisticsNo(logisticsNo);
        boolean update = this.updateById(order);
        if (!update) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 记录日志
        OrderLog log = new OrderLog();
        log.setOrderId(orderId);
        log.setOrderType(order.getOrderType());
        log.setType(OrderLogType.DELIVER);
        log.setMemo("订单发货");
        this.orderLogMapper.insert(log);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliverUpdate(String orderId, String logisticsCompany, String logisticsNo) {
        Order order = this.getById(orderId);
        Assert.isTrue(order != null, "订单不存在");
        if (!"-1".equals(logisticsCompany)) {
            Assert.isTrue(StringUtils.hasText(logisticsNo), "物流单号不能为空");
            LogisticsCompany company = this.logisticsCompanyService.findByCode(logisticsCompany);
            Assert.notNull(company, "物流公司不存在");
            logisticsCompany = company.getName();
        }

        order.setLogisticsCompany(logisticsCompany);
        order.setLogisticsNo(logisticsNo);
        boolean update = this.updateById(order);
        if (!update) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }

        // 记录日志
        OrderLog log = new OrderLog();
        log.setOrderId(orderId);
        log.setOrderType(order.getOrderType());
        log.setType(OrderLogType.DELIVER);
        log.setMemo("订单发货");
        this.orderLogMapper.insert(log);
    }

    @Override
    public QueryTrackResp orderTrace(String orderId) {
        Order order = this.getById(orderId);
        Assert.notNull(order, "订单不存在");
        if (!StringUtils.hasText(order.getLogisticsCompany()) || !StringUtils.hasText(order.getLogisticsNo())) {
            return null;
        }
        return this.deliveryService.queryTrack(order.getLogisticsCompany(), order.getLogisticsNo(), order.getPhone());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelGroupon(Long grouponLogId, String orderId) {
        Order order = this.getById(orderId);
        if (order == null || !Objects.equals(order.getOrderType(), OrderType.GROUPON)) {
            log.warn("团购订单[{}]不存在！", orderId);
            return;
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.WAIT_DELIVER)) {
            log.warn("团购订单[{}]状态已流转至[{}]，无法取消", orderId, order.getStatus());
            return;
        }

        // 积分、余额退还
        returnBalanceAndStock(order);
        // 退还余额
        if (order.getRealAmount().compareTo(BigDecimal.ZERO) > 0) {
            Payment payment = this.paymentService.getByOrderId(order.getId());
            // 查找支付信息
            String outRefundNo = this.redisService.getNextStandardCodeByDayClean("14", 7);

            Payment refundPayment = new Payment();
            refundPayment.setId(outRefundNo);
            BigDecimal realAmount = order.getRealAmount();
            refundPayment.setAmount(realAmount);
            refundPayment.setExpire(LocalDateTime.now().plusHours(2));
            refundPayment.setMemo("商城退款");
            refundPayment.setMethod(PaymentMethod.ONLINE);
            refundPayment.setOrderId(order.getId());
            refundPayment.setPaymentMethod(payment.getPaymentMethod());
            refundPayment.setPaymentPluginId(payment.getPaymentPluginId());
            refundPayment.setStatus(PaymentStatus.SUCCESS);
            refundPayment.setMemberId(order.getMemberId());
            refundPayment.setOrderType(order.getOrderType());

            WxPayRefundRequest refundRequest = WxPayRefundRequest.newBuilder()
                    .outTradeNo(payment.getId())
                    .outRefundNo(outRefundNo)
                    .refundDesc("团购订单["+orderId+"]未成团退还")
                    .refundFee(MoneyUtil.toFee(realAmount))
                    .totalFee(MoneyUtil.toFee(realAmount))
                    .build();
            try {
                log.error("微信订单退款，orderId:{}, refundAmount:{}, request:{}", order.getId(), realAmount, refundRequest);
                WxPayConfig payConfig = new WxPayConfig();
                // todo 转为查库
                payConfig.setAppId("wxba84637dfefe6ad2");
                payConfig.setMchId("1657615378");
                payConfig.setMchKey("ffc838495d474e50ad2000f96ef7d7ee");
                payConfig.setKeyPath("/data/project/mifen/apiclient_cert.p12");
                WxPayService payService = new WxPayServiceImpl();
                payService.setConfig(payConfig);
                WxPayRefundResult result = payService.refund(refundRequest);
                if (result.getResultCode().equals("FAIL")) {
                    //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL).message(result.getErrCodeDes()));
                }
                refundPayment.setTradeNo(result.getTransactionId());
            } catch (WxPayException e) {
                log.error("微信订单退款异常:[{}]", refundRequest, e);
                //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL).message(e.getMessage()));
            }
            this.paymentService.save(refundPayment);
        }

        GrouponLog grouponLog = this.grouponLogService.getById(grouponLogId);
        Assert.notNull(grouponLog, "团购记录[{"+grouponLogId+"}]不存在！");
        grouponLog.setEndTime(LocalDateTime.now());
        grouponLog.setIsRefund(1);
        grouponLog.setStatus(GrouponStatus.FAILURE);
        this.grouponLogService.updateById(grouponLog);
    }

    @Autowired
    public void setOrderItemService(IOrderItemService orderItemService) {
        this.orderItemService = orderItemService;
    }

    @Autowired
    public void setOrderLogMapper(OrderLogMapper orderLogMapper) {
        this.orderLogMapper = orderLogMapper;
    }

    @Autowired
    public void setShopkeeperGoodsMapper(ShopkeeperGoodsMapper shopkeeperGoodsMapper) {
        this.shopkeeperGoodsMapper = shopkeeperGoodsMapper;
    }

    @Autowired
    public void setShopkeeperGoodsSpecsMapper(ShopkeeperGoodsSpecsMapper shopkeeperGoodsSpecsMapper) {
        this.shopkeeperGoodsSpecsMapper = shopkeeperGoodsSpecsMapper;
    }

    @Autowired
    public void setGoodsMapper(GoodsMapper goodsMapper) {
        this.goodsMapper = goodsMapper;
    }

    @Autowired
    public void setGoodsSpecsMapper(GoodsSpecsMapper goodsSpecsMapper) {
        this.goodsSpecsMapper = goodsSpecsMapper;
    }

    @Autowired
    public void setGoodsCommentMapper(GoodsCommentMapper goodsCommentMapper) {
        this.goodsCommentMapper = goodsCommentMapper;
    }

    @Autowired
    public void setLogisticsCompanyService(ILogisticsCompanyService logisticsCompanyService) {
        this.logisticsCompanyService = logisticsCompanyService;
    }

    @Autowired
    public void setDeliveryService(IDeliveryService deliveryService) {
        this.deliveryService = deliveryService;
    }

    @Autowired
    public void setOrderCommentService(IOrderCommentService orderCommentService) {
        this.orderCommentService = orderCommentService;
    }

    @Autowired
    public void setMemberMapper(MemberMapper memberMapper) {
        this.memberMapper = memberMapper;
    }

    @Autowired
    public void setSettingsService(ISettingsService settingsService) {
        this.settingsService = settingsService;
    }

    @Autowired
    public void setShopkeeperPointsLogService(ShopkeeperPointsLogService shopkeeperPointsLogService) {
        this.shopkeeperPointsLogService = shopkeeperPointsLogService;
    }

    @Autowired
    public void setShopkeeperService(ShopkeeperService shopkeeperService) {
        this.shopkeeperService = shopkeeperService;
    }

    @Autowired
    public void setMemberPointsService(MemberPointsService memberPointsService) {
        this.memberPointsService = memberPointsService;
    }

    @Autowired
    public void setGrouponService(GrouponService grouponService) {
        this.grouponService = grouponService;
    }

    @Autowired
    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @Autowired
    public void setRedisService(IRedisService redisService) {
        this.redisService = redisService;
    }

    @Autowired
    public void setGrouponLogService(GrouponLogService grouponLogService) {
        this.grouponLogService = grouponLogService;
    }
}
